<script src="static/scripts/jquery.min.js"></script>
<link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="static/bootstrapQ/qiao.css" rel="stylesheet">
<script type="text/javascript" src="static/bootstrapQ/qiao.js"></script>
<link href="static/markdown/css/editormd.min.css" rel="stylesheet">
<script type="text/javascript" src="js/common.js"></script>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/DocSys.js"></script>
<style type="text/css" media="screen">
  body {
      overflow: hidden;
  }

  #editor {
      margin: 0 0 0 0;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
  }
</style>
<!--编辑器的样式提取-->
<style>
	.stackedit-no-overflow {
		overflow: hidden;
	}

	.stackedit-container {
		background-color: rgba(160, 160, 160, 0.5);
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 9999;
	}

	.stackedit-hidden-container {
		position: absolute;
		width: 10px;
		height: 10px;
		left: -99px;
	}

	.stackedit-iframe-container {
		background-color: #fff;
		position: absolute;
		margin: auto;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		height: 100%;
		width: 100%;
		border-radius: 2px;
		overflow: hidden;
	}

	.stackedit-iframe {
		position: absolute;
		height: 100%;
		width: 100%;
		border: 0;
		border-radius: 2px;
	}

	@media (max-width: 740px) {
		.stackedit-iframe-container {
			height: 100%;
			width: 100%;
			border-radius: 0;
		}

		.stackedit-iframe {
			border-radius: 0;
		}
	}

	.stackedit-close-button {
		position: absolute !important;
		box-sizing: border-box !important;
		width: 38px !important;
		height: 36px !important;
		margin: 4px !important;
		padding: 0 4px !important;
		text-align: center !important;
		vertical-align: middle !important;
		text-decoration: none !important;
	}
</style>
<div id="textEditor">
	<div class="textEditorContent" style="min-height: 600px;">
		<div id="editor">
			<div class="stackedit-container">
				<div class="stackedit-iframe-container">
					<iframe class="stackedit-iframe" src="#" width="100%" height="100%"></iframe>
				</div>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">
	function GetRequest() {
		var url = location.search; //获取url中"?"符后的字串
		var theRequest = {};
		if (url.indexOf("?") !== -1) {
			var str = url.substr(1);
			var strs = str.split("&");
			for(var i = 0; i < strs.length; i ++) {
				theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
			}
		}
		return theRequest;
	}
	var params = GetRequest();
	var docid = params['docid'];
	//获取artDialog父窗口传递过来的参数
	var artDialog2 = window.top.artDialogList['ArtDialog'+docid];
	if (artDialog2 == null) {
		artDialog2 = window.parent.artDialogList['ArtDialog' + docid];
	}
	// 定义成员变量
	var docInfo = artDialog2.config.data; // 获取对话框传递过来的数据
	var docText = "";
	var tmpSavedDocText = "";
	var isContentChanged = false;
	var isReadOnly = false;
	var editState = false;
	

	//页面加载完成处理函数
	$(document).ready(function() {
		// 初始化文档信息
		docInfoInit();
		// 加载文档窗口，传入文档加载成功回调函数和加载失败函数
		console.log("stackeditEditorForArt");
		
		//history file or file in zip is readonly
		checkAndSetIsReadOnly(docInfo);
		
		getDocText(docInfo, showText, showErrorMessage);
	});
	
	function checkAndSetIsReadOnly(docInfo)
	{
		if(docInfo.isZip && docInfo.isZip == 1)
		{
			isReadOnly = true;
			return;
		}
		if(docInfo.isHistory && docInfo.isHistory == 1)
		{
			isReadOnly = true;
			return;
		}
	}
	
	/**
	 * 文档信息初始化方法
	 */
	function docInfoInit() {
		// 为空时获取文档的后缀
		if(docInfo.fileSuffix !==  undefined || docInfo.fileSuffix !== "") {
			docInfo.fileSuffix = getFileSuffix(docInfo.name);
		}
	}
	/**
	 * 文档加载类
	 * @param docText_ 文档内容
	 * @param tmpSavedDocText_ 临时保存文档内容（暂时未使用）
	 */
	function showText(docText_, tmpSavedDocText_) {
		// 传入staticedit插件地址和文件内容，获取staticedit插件指定路径
		var url = getStaticEditUrl("/DocSystem/web/static/stackedit/dist/index.html",docText_);
		// 获取iframe并设置其src路径，渲染stackEdit编辑器，加载待修改markdown文件
		var stackEditIframeEl = $(".stackedit-iframe");
		stackEditIframeEl.prop("src",url);

		// Listen to StackEdit events and apply the changes to the textarea.
		//监听iframe发来的消息
		window.addEventListener('message', messageHandler);
		// 设置定时0.5s后设置页面为只读
		setTimeout(function () {
			editState = false;
			setStaticEditReaOnly(false);
		},500)
	}

	/**
	 * staticEdit消息事件处理
	 *
	 * @param event 事件对象
	 */
	function messageHandler(event) {
		switch (event.data.type) {
			case 'ready':
				// iframe 页面加载完成,设置当前页面为只读
				editState = false;
				setStaticEditReaOnly(false);
				break;
			case 'fileChange':
				if(isReadOnly == false)
				{
					//收到iframe文件改动消息
					var file = event.data.payload;
					docText = file.content.text;
					isContentChanged = true;
				}
				break;
			case 'close':
				//收到iframe的关闭消息
				var artDialog = top.dialog.get(window);
				artDialog.close();
				break;
			case 'saveChange':
				if(isContentChanged) {
					//执行文档保存操作
					saveDoc();
				}
				break;
			case 'changeView':
				//当文档处于编辑状态要切换只读时触发
				if(event.data.flag)
				{
					console.log("编辑器退出入编辑状态...");
					if(editState == true)
					{
						exitEdit();
					}
				}
				else
				{
					console.log("编辑器已进入编辑状态...");
					if(editState == false)
					{
						enableEdit();
					}
				}
				break;
			case 'uploadImages':
				var images = event.data.payload.content.images;
				if (images && images.length > 0) {
					// 仅上传第一个传输过来的图片
					uploadMarkdownPic(images[0]);
				}
				break;
			default:
		}
	}

	/**
	 * 图片上传
	 */
	function uploadMarkdownPic(file) {
		var xhr = new XMLHttpRequest();
		var form = new FormData();
		form.append("editormd-image-file", file);
		//上传表单
		var imgName =  file.lastModified + "_" + file.name;
		var path = base64_urlsafe_encode(docInfo.path);
		var name = base64_urlsafe_encode(docInfo.name);
		var imageUploadURL = "/DocSystem/Doc/uploadMarkdownPic.do?reposId=" + docInfo.vid + "&docId=" + docInfo.docId + "&path="+ path + "&name="+ name + "&imgName=" + imgName;
		if(docInfo.shareId) {
			imageUploadURL="&shareId="+docInfo.shareId;
		}
		xhr.open("post", imageUploadURL);
		xhr.send(form);
		//设置异步上传状态变化回调处a理函数
		xhr.onreadystatechange = function() {
			if(xhr.status == 200) {
				if(xhr.readyState != 4) {
					//文件上传未结束
					return;
				}
				//上传成功！
				var ret = JSON.parse(xhr.responseText);
				if(1 == ret.success) {
					var stackeditEl = $(".stackedit-iframe");
					if (stackeditEl !== undefined) {
						var origin = window.location.protocol + '//' + window.location.host;
						var imgUrl = origin + ret.url;
						stackeditEl[0].contentWindow.postMessage({"type":"uploadCompleted","imgUrl":imgUrl},"*");
					}
				}
				else {
					//上传失败
					console.error("上传失败：" + ret.msgInfo);
				}
			}else{
				if(xhr.status < 300) {
					//不是真正的异常
					return;
				}
				//上传失败
				console.error("系统异常: 上传异常！");
			}
		};
	}

	/**
	 * stackEdit插件加载路径初始化，在原始路径上拼装文件信息，域信息
	 *
	 * @param url 插件路径
	 * @param doc_text 文档内容
	 * @return 拼装后携带文件内容的url路径
	 */
	function getStaticEditUrl(url,doc_text) {
		var origin = window.location.protocol + '//' + window.location.host;
		var fileName = docInfo.name;
		var params = {
			origin: origin,
			fileName: fileName,
			contentText: doc_text,
			silent: false
		};
		var serializedParams = Object.keys(params).map(function (key) {
			return key + '=' + encodeURIComponent(params[key] || '');
		}).join('&');
		var hash = '#' + serializedParams;
		return url+hash;
	}

	/**
	 * 设置编辑器的编辑状态为只读
	 *
	 * @param editFlag false代表编辑状态，true代表只读状态
	 */
	function setStaticEditReaOnly(editFlag) {
		var stackeditEl = $(".stackedit-iframe");
		if (stackeditEl !== undefined) {
			stackeditEl[0].contentWindow.postMessage({"type":"toggleEditor","flag":editFlag},"*")
		}
	}

	/**
	 * 设置编辑器的保存按钮的开启和禁用
	 *
	 * @param editFlag false代表编辑状态，true代表只读状态
	 */
	function disabledEditState(editFlag) {
		var stackeditEl = $(".stackedit-iframe");
		if (stackeditEl !== undefined) {
			stackeditEl[0].contentWindow.postMessage({"type":"updateEditState","flag":editFlag},"*")
		}
	}

	/**
	 * 保存文档
	 */
    function saveDoc() {
		$.ajax({
            url : "/DocSystem/Doc/updateDocContent.do",
            type : "post",
            dataType : "json",
            data : {
                reposId: docInfo.vid,
            	docId : docInfo.docId,
            	path: docInfo.path,
                name: docInfo.name,
            	content : docText,
            	docType: 1, //RealDoc
                shareId: docInfo.shareId,
            },
            success : function (ret) {
                if( "ok" === ret.status ){
                    isContentChanged = false;
					disabledEditState(true);
                    bootstrapQ.msg({
								msg : "保存成功 :" + (new Date()).toLocaleDateString(),
								type : 'success',
								time : 1000,
					});
				}else {
                    bootstrapQ.alert("保存失败:"+ret.msgInfo);
                }
            },
            error : function () {
                bootstrapQ.alert("保存失败:服务器异常");
            }
        });
    }

    function enableEdit()
    {
		console.log("enableEdit()");
		if(!docInfo.docId || docInfo.docId == 0)
		{
			editState = false;
			setStaticEditReaOnly(false);
			return;
		}

		$.ajax({
			url : "/DocSystem/Doc/lockDoc.do",
			type : "post",
			dataType : "json",
			data : {
				lockType : 1, //LockType: Online Edit
				reposId : docInfo.vid,
				docId : docInfo.docId,
				path: docInfo.path,
				name: docInfo.name,
				docType: 1,
                shareId: docInfo.shareId,
			},
			success : function (ret) {
				if( "ok" == ret.status)
				{
					console.log("enableEdit() ret.data",ret.data);
					$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","red");

					editState = true; //编辑器已处于编辑状态不需要切换
					return;
 				}
				else
				{
					//锁定失败，切换编辑状态，但要避免触发exitEdit
					editState = false;
					setStaticEditReaOnly(false);
					return;
				}
			},
			error : function ()
			{
				editState = false;
				setStaticEditReaOnly(false);
				return;
			}
		});
    }

	//退出文件编辑状态
    function exitEdit() {
		console.log("exitEdit()  docInfo.docId:" + docInfo.docId);
		if(!docInfo.docId || docInfo.docId == 0)
		{
			editState = false;
			setStaticEditReaOnly(false);
			return;
		}

		$.ajax({
			url : "/DocSystem/Doc/unlockDoc.do",
			type : "post",
			dataType : "json",
			data : {
				lockType : 1, //unlock the doc
				reposId : docInfo.vid,
            	docId : docInfo.docId,
				path: docInfo.path,
				name: docInfo.name,
				docType: 1,
                shareId: docInfo.shareId,
			},
			success : function (ret) {
				if( "ok" == ret.status)
				{
					console.log("exitEdit() ret:",ret.data);
					$("[dataId='"+ docInfo.docId +"']").children("div:first-child").css("color","black");
					editState = false;
					return;
 				}
				else
				{
					editState = true;
					setStaticEditReaOnly(true);
					return;
				}
			},
			error : function ()
			{
				editState = true;
				setStaticEditReaOnly(true);
				return;
			}
		});
	}
</script>
